﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Krypton.Navigator;
using NesEmu.Core;
using NesEmu.Explorer.Controls;
using NesEmu.Explorer.Properties;

namespace NesEmu.Explorer.Pages
{
    public partial class DisassemblerPage : UserControl
    {
        private readonly NesCodeEditor _editor = new NesCodeEditor();

        private DisassemblerPage()
        {
            InitializeComponent();
        }

        public DisassemblerPage(FrmMain parent, string code)
            : this()
        {
            _editor.IsReadOnly = true;
            _editor.SyntaxHighlightingDefinitionResourceName = "NesEmu.Explorer.6502.xshd";
            _editor.Text = code;
            elementHost.Child = _editor;
        }

        public sealed class Page : KryptonPage
        {
            public const string PageName = "A7312C4A-83A8-4C23-B7FB-26F15BB361FF";

            private readonly DisassemblerPage _ctrl;

            public Page(FrmMain parent, object? args = null)
            {
                if (args is not FileBrowserPage.FileBrowserItemTag selectedNesFile)
                    throw new ArgumentException(@"Selected node doesn't have NES file information.", nameof(args));

                Text = @$"DASM - {Path.GetFileName(selectedNesFile.FilePath)}";
                TextTitle = Text;
                TextDescription = TextTitle;
                ImageSmall = Resources.DisassemblyWindow_6536;

                if (selectedNesFile.Cartridge is null)
                {
                    throw new InvalidOperationException("Cartridge is empty.");
                }

                var tmpEmu = new Emulator();
                tmpEmu.InstallCartridge(selectedNesFile.Cartridge);
                var code = tmpEmu.Disassemble();

                _ctrl = new DisassemblerPage(parent, code)
                {
                    Dock = DockStyle.Fill
                };

                Controls.Add(_ctrl);
            }
        }
    }
}
